﻿using Core;
using Core.ReadAndWrite;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsForms
{
    public partial class FormHocPhan : Form
    {
        
        public FormHocPhan()
        {
            InitializeComponent();
        }
        private QuanLiDSHocPhan ql = new QuanLiDSHocPhan();

        private void FormHocPhan_Load(object sender, EventArgs e)
        {
            
        }
        private void LoadData(string path)
        {
         List<BaseData>Ds=  DataSource.Instance.ReadHocPhan(path);
         LoadData(Ds);
         
        }

        private void LoadData(List<BaseData> Ds)
        {
            lvhienthi.Items.Clear();
            ql.ListHocPhan.Clear();
            foreach (var item in Ds)
            {
                ListViewItem it = new ListViewItem((item as HocPhan).MaHocPhan);
                it.SubItems.Add((item as HocPhan).TenHocPhan);
                it.SubItems.Add((item as HocPhan).SoTC + "");
                it.SubItems.Add((item as HocPhan).LoaiHP + "");

                ql.Add(item);
                lvhienthi.Items.Add(it);
              

            }
        }

        private void loadHP_Click(object sender, EventArgs e)
        {
            LoadData(QuanLiDSHocPhan.Instance.ListHocPhan);
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var dialog = new OpenFileDialog();
                dialog.Multiselect = false;
                dialog.Filter = "All files (*.*)|*.*|Text files (*.txt)|*.txt|Data files (*.dat)|*.dat";
                dialog.InitialDirectory = Application.ExecutablePath;
                if (dialog.ShowDialog(this) == DialogResult.OK)
                {
                    LoadData(dialog.FileName);
                   
                }
                
            }
            catch
            {
                 
                MessageBox.Show("File bạn chọn không đúng cấu trúc", "Lỗi");
            }
          
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (File.Exists("Dshp.txt"))
            {
              DialogResult dg=  MessageBox.Show("file đã có bạn thật sự muốn lưu thay đổi không","",MessageBoxButtons.OKCancel,MessageBoxIcon.Warning);
              if (dg == DialogResult.OK)
              {
                  DataSource.Instance.WriteTo(ql.ToString(), "Dshp.txt");
                  QuanLiDSHocPhan.Instance.getHocPhan();
              } 

              
            }
            else DataSource.Instance.WriteTo(ql.ToString(), "Dshp.txt"); 
        }
    }
}
